// component/loginPicker/loginPicker.js
import ajax from "../../utils/index"
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    shareId: String
  },

  /**
   * 组件的初始数据
   */
  data: {
    agreement: false, // 服务协议
    loginCode: null,
    showMode: false,
    userInfo: null
  },

  /**
   * 组件的方法列表
   */
  methods: {
    /**
      * 服务协议点击事件
      */
    agreement_change(event) {
      this.setData({ agreement: event.detail })
    },
    /**
   * 获取登录code
   */
    async getLoginCode() {
      const res = await ajax.getLoginCode()
      this.data.loginCode = res.code
    },
    /**
   * 登录事件
   */
    async loginEvent() {
      const { agreement, shareId } = this.data;
      if (!agreement) return ajax.showToast('请同意并阅读盈联易单配用户服务协议');
      ajax.showLoading()
      const wxUserInfo = await ajax.getUserPro().finally(() => wx.hideLoading());
      if (wxUserInfo.errMsg != 'getUserProfile:ok') return;
      wxUserInfo.code = this.data.loginCode, wxUserInfo.shareId = shareId || '', ajax.showLoading();
      const res = await ajax.post('/wx/user/login', wxUserInfo).finally(() => wx.hideLoading());
      const { phone, user, token } = res.data;
      if (!phone) return this.setData({ userInfo: user, showMode: true });
      wx.setStorageSync('Token', token), wx.setStorageSync('userInfo', user);
      await ajax.showSuccess('登录成功');
      wx.setStorageSync('pageRoles', 0)
      this.triggerEvent('success')
    },
    /**
   * 获取手机号信息, 用户信息
   */
    async getPhoneNumber(event) {
      if (event.detail.errMsg !== 'getPhoneNumber:ok') return wx.navigateTo({ url: '/pages/bindingMobile/bindingMobile' })
      ajax.showLoading();
      const entity = event.detail, { loginCode, userInfo } = this.data;
      entity.code = loginCode, entity.userId = userInfo.id;
      const res = await ajax.post('/wx/user/phone', entity).finally(() => wx.hideLoading());
      const { user, token } = res.data;
      wx.setStorageSync('Token', token), wx.setStorageSync('userInfo', user);
      await ajax.showSuccess('登录成功');
      wx.setStorageSync('pageRoles', 0)
      this.triggerEvent('success')
    },
    /**
    * 关闭绑定手机号弹窗
    */
    modeCancel() {
      this.setData({ showMode: false })
    },
    /**
     * 取消事件
     */
    cancelEvent() {
      this.triggerEvent('cancel')
    },
  }
})
